/*
 * Resource.cpp
 *
 *  Created on: Jul 28, 2013
 *      Author: zapmunk
 */

#include "headerstop.h"

#include "Resource.h"

#include <fstream>

using std::ifstream;
using std::ios;
using std::string;

uint ProgressTracker::getBytes() const {return bytes;}
uint ProgressTracker::getMaxBytes() const {return maxbytes;}
double ProgressTracker::getProgress() const {
	return (double) bytes / (double) maxbytes;
}

Resource::Resource(const char* path, LoadType loadtype, string name):
		path(path), loadtype(loadtype),
		m_data(NULL), m_size(0),
		data(m_data), size(m_size),
		m_isLoaded(false),
		name(name) {}

/*std::string renderHex(uchar c) {
	std::string s = "";
	uchar d = c/0x10;
	if (d > 9) d += 'A'-10; else d += '0';
	s += d;
	d = c%0x10;
	if (d > 9) d += 'A'-10; else d += '0';
	s += d;
	return s;
}*/

bool Resource::load(ProgressTracker* tracker) {
	ifstream file(path, ios::binary|ios::ate);

	if (!file.is_open()) {
		std::cout << "Could not open " << path << "!" << std::endl;
		return false;
	}

	m_size = (uint)file.tellg();
	file.seekg(0);
	m_data = new char[m_size+1]; m_data[m_size] = 0;
	int pos = 0;

	if (tracker) {
		tracker->bytes = 0;
		tracker->maxbytes = m_size;
	}

	while (pos < m_size) {
		if (pos+READ_BLOCK_SIZE < m_size) {
			file.read(m_data+pos, READ_BLOCK_SIZE);
			pos += READ_BLOCK_SIZE;
		} else {
			file.read(m_data+pos, m_size-pos);
			pos = m_size;
		}
		if (tracker) tracker->bytes = pos;
	}

	/*for (int i = 0; i < m_size; i++) {
		std::cout << renderHex(m_data[i]) << ' ';
	}
	std::cout << "|STOP" << std::endl;*/

	m_isLoaded = true;

	return true;
}

void Resource::unload() {
	if (m_isLoaded) {
		if (m_data) delete[] m_data;
		m_size = 0;
		m_isLoaded = false;
	}
}

Resource::~Resource() {
	unload();
}
